namespace mgp.ads {
    export class QqAppBoxAd implements IAppBoxAd {

        protected _info: IAppBoxAdInfo;

        protected _ad: any;
        protected _closeFun: () => void;

        setInfo(info: IAppBoxAdInfo) {
            this._info = info;
        }

        show(close?: () => void) {
            this._closeFun = close;
            this._ad = this._getAd();
            if (!!this._info.preload) this._info.preload()

            this._ad.load().then(() => {
                if (!!this._info.loadSuccess) this._info.loadSuccess()
                this._ad.show();
            }).catch(err => {
                if (!!this._info.onErr) this._info.onErr()
            });
        }

        destroy() {
            if (!this._ad) return;
            this._ad.offClose(this._onBoxClose.bind(this));
            this._ad.destroy()
            this._ad = null;
        }

        protected _getAd() {
            if (!this._ad) {
                this._ad = window['qq'].createAppBox({
                    adUnitId: this._info.ids[0]
                })
                this._ad.onClose(this._onBoxClose.bind(this));
            }
            return this._ad;
        }

        protected _onBoxClose() {
            if (!!this._closeFun) this._closeFun()
        }
    }
}